<?php
/*
* Author: Jason ZHENG <zmj522008@hotmil.com>
* Date  : 2018/05/21
* Class : User 用户管理
*/
namespace app\index\controller;

use app\common\controller\Helptype;
use app\index\controller\Log\InsertLog;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use app\index\service\MerchantService;

class User extends Controller
{ 

	public function index()
	{
		return 'User account management';
	}

	// 我的钱包记录
	public function my_wallet(Request $request)
	{
		$postData = $request->post();
	
		$days = isset($postData['days']) ? $postData['days']: null;
		if($days == 7 || $days == 30)
		{
			$startDate 	= date('Y-m-d', strtotime('-'.$days.' days'));
			$endDate   	= '2222-01-01 00:00:00';
		}else{
			$startDate 	= isset($postData['start_date']) ? $postData['start_date'] : '1700-01-01 00:00:00';
			$endDate   	= isset($postData['end_date']) ? $postData['end_date'] : '2222-01-01 00:00:00';
		}

		$page 		= isset($postData['page']) ? $postData['page'] : 1;
		$type  = isset($postData['type']) ? $postData['type'] : null;

		$accountDetails = self::account_details($startDate, $endDate, $page, $type);
		$returnData =  [
							'accountBalance' 		=> round(MerchantService::get_balance($this->user_id,1),2),
							'accountNotBalance' 	=> round(MerchantService::get_balance($this->user_id,0),2),
							'accountTotal'			=> round(MerchantService::get_balance($this->user_id,2),2),
							'accountDetails' 		=> $accountDetails['list']
						];
		return ['code' => 666, 'msg' => 'ok', 'data' => $returnData];
	}
	// 获取账户详情（收入和支出明细）
	// params：$startDate => 搜索开始日期， $endDate=> 搜索结束日期 ， $page=> 页数， $operating=> 收入支出（0为充值，1为消费）
	public static function account_details($startDate, $endDate, $page, $type)
	{
        $type = isset($type)?$type==1?[1]:[2]:[1,2];
		$merchant_currency = Db::table('merchant_currency')
			     ->where(['user_id' => Session::get('user.id')])
				 ->where('createtime', '>=', $startDate )
				 ->where('createtime', '<=', $endDate )
				 ->where('type', 'in', $type)
			->paginate(10,false,['query'=>request()->param()])
			->toArray();
		if($merchant_currency['data']){
			foreach($merchant_currency['data'] as $k=>$v){
				$merchant_currency['data'][$k]['money'] = round($v['money'],2);

				if($v['type']==1){
					$getBatchcode = self::get_product($v['batchcode']);
				}else{
					$getBatchcode = [];
				}
				$merchant_currency['data'][$k]['product'] = $getBatchcode;
			}
		}
		$count = Db::table('merchant_currency')
				 ->where(['user_id' => Session::get('user.id')])
				 ->where('createtime', '>=', $startDate )
				 ->where('createtime', '<=', $endDate )
				 ->where('type', 'in', $type)
				 ->count();
		return ['count' => $count, 'list' => $merchant_currency];
	
	}

	/**
	 * @Notes:获取订单信息
	 * @param $batchcode
	 * @return false|\PDOStatement|string|\think\Collection
	 * @author: LiBaoJin
	 * @Time:
	 */
	public static function get_product($batchcode){
		$orders_infos = Db::table('orders_info')->alias('or')
			->join('product p','or.product_id=p.id','LEFT')
			->join('orders o','o.batchcode=or.batchcode','LEFT')
			->join('systematics stt', 'p.brand_id = stt.id', 'LEFT') //品牌
			->join('systematics sy', 'p.systematics_id = sy.id', 'LEFT') //系列
			->join('product_fineness pf','p.product_condition = pf.id','LEFT')//成色
			->field('stt.title brand_title,sy.title systematics_title,pf.value product_condition,o.uniqueOrderNo,p.product_sn,p.product_name,p.pic_url,p.thumb_url')
			->where(['or.batchcode'=>$batchcode])
			->select();
		return $orders_infos;
	}
	/**
	 * @param Request $request
	 * @return array
	 * 用户注册
	 */
	public function register(Request $request){
		$back = ['code'=>666,'msg'=>'ok','data'=>[]];
		$postData = $request->post();
		//验证传过来的参数
		$rules = [
			'phone_number'  => ['regex'=>'/^((13[0-9])|(14[4,7])|(15[0-3,5-9])|16[6]|(17[0,3,5-8])|(18[0-9])|(19[89]))\d{8}$/','require'],
			'password'   => ['require','regex'=>'/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,60}/'],
			'repassword'=>'require|confirm:password',
			'phone_code'=>'require|number'
		];
		$msg = [
			'phone_number.require' => '手机号不能为空',
			'phone_number.regex' => '手机号格式不对',
			'password.require' => '密码不能为空',
			'password.regex' => '密码必须由数字和字母组成',
			'repassword' => '两次密码不一致',
			'phone_code' => '手机验证码错误',
		];
		$rule = $this->validate($postData,$rules,$msg);
		if($rule !== true){
			$back['code'] = -1;
			$back['msg'] = $rule;
			return $back;
		}
		$re_data = Db::table('users')
			->where(['phone'=>$postData['phone_number'],'is_business' => ['in', '1,2']])
			->whereOr('phone='.$postData['phone_number'].' AND '. 'is_staff=1')
			->select();
		if(!empty($re_data)){
			$back['code'] = -1;
			$back['msg'] = '您已注册过！';
			return $back;
		}
		//验证短信
       $reg = Db::table('phone_code')->where(['phone'=>$postData['phone_number'],'code'=>$postData['phone_code']])->find();
		if(empty($reg)){
			$back['code'] = -1;
			$back['msg'] = '验证码错误';
			return $back;
		}
		$postData['system_id'] = isset($postData['system_id'])?$postData['system_id']:1;
        try{
			$res = Db::table('users')->insertGetId([
				'phone'     => $postData['phone_number'],
				'password'  =>$postData['password'],
				'system_id' =>$postData['system_id'],
				'is_business' =>1,
				'createtime' => date('Y:m:d H:i:s',time()),
			]);
			if(!$res){
				$back['code'] = -1;
				$back['msg'] ="系统错误";
				return $back;
			}
			Db::table('business')->insertGetId([
				'business_id'     => $res,
				'business_phone'  =>$postData['phone_number'],
				'createtime' => date('Y:m:d H:i:s',time()),
			]);
			Db::table('user_info')->insertGetId([
				'user_id'     => $res,
				'createtime' => date('Y:m:d H:i:s',time()),
			]);
			return $back;
		} catch(Exception $e){
			$back['code'] = -1;
			$back['msg'] = $e->getMessage();
			return $back;
		}
	}
}   